<!--
 * @Author: doing
 * @Date: 2023-08-10 12:12:49
 * @LastEditors: git config user.name && git config user.email
 * @LastEditTime: 2023-09-02 21:26:23
 * @FilePath: \background-management-system\src\pages\member\index.vue
 * @Description: 
 * 成员管理
 * Copyright (c) 2023 by 1540265624@qq.com, All Rights Reserved. 
-->
<template>
    <div>
        <!-- 卡片视图区域 -->
        <el-card v-loading="isMemberListLoading">
            <!-- 实现表单模块 -->
            <el-form ref="searchRef" :model="searchForm" class="flex">
                    <el-form-item label="成员昵称" class="mr-4" prop="nick_name">
                        <el-input style="width: 150px;" placeholder="请输入成员名称" v-model="searchForm.nick_name"></el-input>
                    </el-form-item>
                    <el-form-item label="职位：" class="mr-4" prop="status">
                        <el-select v-model="searchForm.status" clearable filterable style="width: 85px">
                            <el-option v-for="item in statusOptions" :key="item.code" :label="item.name" :value="item.code">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="findMember" v-permission="['member:search']">
                            <el-icon style="vertical-align: middle;">
                                <search />
                            </el-icon>
                            <span style="vertical-align: middle;">查询</span>
                        </el-button>
                        <el-button @click="ressetForm">
                            <el-icon style="vertical-align: middle;">
                                <RefreshLeft />
                            </el-icon>
                            <span style="vertical-align: middle;">重置</span>
                        </el-button>
                        <el-button type="primary" @click="handleAdd" v-permission="['member:add']">
                            <el-icon style="vertical-align: middle;">
                                <CirclePlus />
                            </el-icon>
                            <span style="vertical-align: middle;">新增</span>
                        </el-button>
                    </el-form-item>
            </el-form>

            <!-- 实现表格和分页 -->
                <el-table :data="memberList" border :table-layout="tableLayout" :cell-style="{ textAlign: 'center' }" :header-cell-style="{textAlign: 'center'}">
                    <el-table-column type="index" label="序号" porp="id"></el-table-column>
                    <el-table-column label="昵称" prop="nickName"></el-table-column>
                    <el-table-column label="头像" prop="avatar" min-width="130px">
                        <template #default="{ row }">
                            <el-image style="width: 100px; height: 100px" :src="row.avatar" :fit="fit">
                                <template #error>
                                    <div class="image-slot">
                                        <el-icon>
                                            <PictureFilled />
                                        </el-icon>
                                    </div>
                                </template>
                            </el-image>
                        </template>
                    </el-table-column>
                    <el-table-column label="年龄" prop="age"></el-table-column>
                    <el-table-column label="成员技能" prop="duty"></el-table-column>
                    <el-table-column label="成员简介" prop="description"></el-table-column>
                    <el-table-column label="职位" prop="status">
                        <template v-slot="scope">
                            <el-tag v-if="scope.row.status === 0">队长</el-tag>
                            <el-tag v-else-if="scope.row.status === 1">副队长</el-tag>
                            <el-tag v-else-if="scope.row.status === 2">核心成员</el-tag>
                            <el-tag v-else-if="scope.row.status === 3">正式成员</el-tag>
                            <el-tag v-else >见习成员</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" prop="isjob">
                        <template v-slot="scope">
                            <el-tag type="warning" v-if="scope.row.isjob === 0">离职</el-tag>
                            <el-tag type="success" v-else >任职</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="更新时间" prop="updateDate">
                        <template  #default="{ row }">
                            {{ formatTime(row.updateDate) }}
                        </template>
                    </el-table-column>
                   
                    <el-table-column label="操作" width="auto" min-width="280px">
                        <template v-slot="scope">
                            <el-row :gutter="20" class="flex justify-center">
                                <el-button type="success" @click="handleEdit(scope.row)" icon="Edit" class="btn"
                                v-permission="['member:edit']" 
                                >
                                    编辑
                                </el-button>
                                <el-button type="danger" @click="handleDelete(scope.row.id)" icon="Delete" class="btn"
                                v-permission="['member:delete']"
                                >
                                    删除
                                </el-button>
                            </el-row>
                        </template>
                    </el-table-column>
                </el-table>

            <el-pagination v-model:current-page="page.current" v-model:page-size="page.size"
                :page-sizes="[20,50,100]" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />

        </el-card>

        <!-- 抽屉组件 -->
        <form-drawer ref="formDrawerRef" :title="drawerTitile" :destroyOnClose="true" @submit="drawerSubmit" @clean="cleanForm">
            <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" size="small">
                <el-form-item label="图片：" prop="avatar">
                    <!-- 上传图片 -->
                    <el-upload class="avatar-uploader" action="" accept="image/*" :show-file-list="false"
                        :http-request="uploadMainImg">
                        <img v-if="form.avatar" :src="form.avatar" class="avatar">
                        <i v-else class="avatar-uploader-icon">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </i>
                    </el-upload>
                </el-form-item>
                <el-form-item prop="nickName" label="昵称">
                    <el-input v-model="form.nickName" placeholder="昵称不能为空"></el-input>
                </el-form-item>
                <el-form-item prop="birthDay" label="出生日期">
                    <el-date-picker
                        v-model="form.birthDay"
                        type="date"
                        placeholder="请选择日期"
                        format="YYYY/MM/DD"
                    />
                </el-form-item>
                <el-form-item label="职位" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="0">队长</el-radio>
                        <el-radio :label="1">副队长</el-radio>
                        <el-radio :label="2">核心成员</el-radio>
                        <el-radio :label="3">正式成员</el-radio>
                        <el-radio :label="4">见习成员</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="状态" prop="isjob">
                    <el-radio-group v-model="form.isjob">
                        <el-radio :label="1">任职</el-radio>
                        <el-radio :label="0">离职</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item prop="duty" label="成员技能">
                    <el-input v-model="form.duty" placeholder="成员技能不能为空"></el-input>
                </el-form-item>
                <el-form-item prop="description" label="技能描述">
                    <el-input v-model="form.description" placeholder="描述不能为空"></el-input>
                </el-form-item>
            </el-form>
        </form-drawer>
    </div>
</template>
<script setup>
import { computed, ref, reactive, nextTick, onMounted } from 'vue'
import FormDrawer from '~/components/FormDrawer.vue'
import {
    showModal,
    toast,
    formatTime
} from '~/composables/util.js'
import {
    searchMember,
    updataMember,
    deleteMember,
    addMember,
    uploadPic,
    deletePic
} from '~/api/member.js'
import { Warning } from '@element-plus/icons-vue';
//初始化数据开始
const fit = ref('contain')
const tableLayout = ref('fixed')
const isAddOrEdit = ref(true)
const isMemberListLoading = ref(false)
const drawerTitile = computed(() => isAddOrEdit.value ? '新增' : '修改')
const memberList = ref([])
const page = reactive({
    current: 1,
    size: 20,
    total: 0
})
const Init = async function () {
    isMemberListLoading.value = true
    const body = { ...page,...searchForm }
    console.log('传递参数为')
    console.log(body)

    await searchMember(body).then(res=>{
        memberList.value = res.data.data.records
        page.total = res.data.data.total
    })
    isMemberListLoading.value = false
}


onMounted(() => {
    Init()
})

//初始化数据结束

//分页内容开始(待开发)
const disabled = ref(false)
const background = ref(true)

const handleSizeChange = async function () {
    Init()
}
const handleCurrentChange = function () {
    Init()
}
//分页内容结束

//操作栏开始
//删除操作
const handleDelete = function (id) {
    showModal('是否要删除该数据?').then(async () => {
        toast('正在删除中...', 'info', false, 3000)
        await deleteMember(id).then(res => {
            toast('删除成功')
            //将页面引导到第一页
            ressetForm()
        }).catch(err=>{
            throw err
        })
    }).catch(err=>{
        console.log(err)
    })
}
//删除结束


//编辑抽屉组件开始
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({})
const oldImageUrl = ref('')
const isSubmit = ref(false)

//表单验证规则
const rules = {
    nickName: [
        {
            required: true,
            message: '昵称不能为空',
            trigger: 'blur'
        },
    ],
    duty: [
        {
            required: true,
            message: '成员技能不能为空',
            trigger: 'blur'
        },
    ],
    description: [
        {
            required: true,
            message: '技能描述不能为空',
            trigger: 'blur'
        },
    ],
}
//打开抽屉
const handleEdit = async function (item) {
    console.log(item)
    isAddOrEdit.value = false
    formDrawerRef.value.open()
    await nextTick(()=>{
        form.id = item.id
        form.nickName = item.nickName
        form.avatar = item.avatar
        form.birthDay = item.birthDay
        form.duty = item.duty
        form.description = item.description
        form.status = item.status
        form.isjob = item.isjob
        oldImageUrl.value = item.avatar
    }) 
}
//新增操作
const handleAdd = async function () {
    console.log(form)
    isAddOrEdit.value = true
    //重新进行初始化
    formDrawerRef.value.open()
    formDrawerRef.value.hideLoading()
    
    await nextTick(()=>{
        delete form.id
        form.status = 0
        form.isjob = 1
    })
}

// 删除图片
const deleteImg = function (imageUrl) {
    // 进行编辑的操作
        // 发送请求删除数据库中的原本图片链接
        deletePic(imageUrl).then(res => {
            toast('删除图片成功')
        }).catch(err=>{
            console.log(err)
        })
}


//上传图片
const uploadMainImg = function (file) {
    //创建表单结构
    console.log(file)
    const data = new FormData()
    data.append('file', file.file)

    uploadPic(data).then(res => {
        // 回显图片
        console.log(res)
        form.avatar = res.data.data
        // // 将之前的图片删除，
        if(oldImageUrl.value !== ''){
            deleteImg(oldImageUrl.value)
        }
        oldImageUrl.value = res.data.data
    }).catch(error => {
        console.log(error)
        toast('上传失败', "error")
    })
}



const drawerSubmit = async () => {
    const data = {...form}
    console.log('提交的数据为:')
    console.log(data)
    formRef.value.validate(async (valid) => {
        formDrawerRef.value.showLoading()
        if (!valid) {
            formDrawerRef.value.hideLoading()
            return false
        } else {
            const fn = isAddOrEdit ? addMember(data) : updataMember(data)
            await fn
                .then(res => {
                    console.log(res)
                    isSubmit.value = true
                    formDrawerRef.value.close()
                    toast(drawerTitile.value + '成功')
                    //将分页内容至于第一页
                    ressetForm()
                })
                .finally(() => {
                    isSubmit.value = false
                    formDrawerRef.value.hideLoading()
                })
        }
    })
}
const cleanForm = function(){
    if(form.avatar && !isSubmit.value && isAddOrEdit.value){
        deleteImg(form.avatar)
    }
    formRef.value.resetFields()
}
//编辑抽屉组件结束

//操作栏结束


//查找按钮 重置按钮 新增按钮数据开始
const searchRef = ref(null)
const searchForm = reactive({})
const statusOptions = [
    { code: 0, name: '队长' },
    { code: 1, name: '副队长' },
    { code: 2, name: '核心成员' },
    { code: 3, name: '见习成员' }
]
//查找操作
const findMember = async function () {
    page.current = 1
    Init()
}
//重置操作
const ressetForm = function(){
    searchRef.value.resetFields()
    page.current = 1
    Init()
}
//查找按钮 重置按钮 新增按钮数据结束

</script>
<style scoped>
.form {
    @apply flex justify-start items-center
}

.btn{
    margin: 0 10px;
}


.image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

</style>